"""
返回码枚举定义

使用枚举类型定义系统中使用的所有返回码，实现错误码与返回信息的集中管理
"""

from enum import Enum
from typing import Optional, Dict


class BaseCodeEnum(Enum):
    """
    基础枚举类，所有返回码枚举的基类
    
    提供统一的接口来获取错误码和描述信息
    """

    def __new__(cls, value, message: str = ""):
        """创建新的枚举实例"""
        obj = object.__new__(cls)
        obj._value_ = value
        obj._message_ = message
        return obj

    @property
    def code(self) -> int:
        """获取状态码"""
        return self.value

    @property
    def message(self) -> str:
        """获取状态码描述"""
        return self._message_

    @classmethod
    def get_by_code(cls, code: int) -> Optional['BaseCodeEnum']:
        """根据状态码获取对应的枚举值"""
        for item in cls:
            if item.code == code:
                return item
        return None

    @classmethod
    def get_message(cls, code: int) -> str:
        """根据状态码获取描述信息"""
        enum_item = cls.get_by_code(code)
        return enum_item.message if enum_item else f"未知状态码: {code}"


class ReturnCode(BaseCodeEnum):
    """
    通用返回码枚举
    
    定义系统中通用的返回码，包括成功和基础错误类型
    """

    # 成功状态码
    SUCCESS = (200, "操作成功")
    OK = (200, "操作成功")

    # 客户端错误码
    BAD_REQUEST = (400, "请求参数错误")
    UNAUTHORIZED = (401, "未授权访问")
    FORBIDDEN = (403, "禁止访问")
    NOT_FOUND = (404, "资源未找到")
    METHOD_NOT_ALLOWED = (405, "方法不被允许")

    # 服务器错误码
    INTERNAL_SERVER_ERROR = (500, "服务器内部错误")
    SERVICE_UNAVAILABLE = (503, "服务不可用")
    GATEWAY_TIMEOUT = (504, "网关超时")


class GeneralErrorCode(BaseCodeEnum):
    """
    通用错误码枚举
    
    定义系统中通用的业务错误码
    """

    INVALID_PARAMETER = (4001, "参数无效")
    MISSING_PARAMETER = (4002, "缺少必要参数")
    INVALID_FORMAT = (4003, "格式无效")
    PERMISSION_DENIED = (5401, "权限被拒绝")


class TTSErrorCode(BaseCodeEnum):
    """
    TTS相关错误码枚举
    
    定义文本转语音服务相关的错误码
    """

    CONVERSION_FAILED = (4101, "文本转语音失败")
    VOICE_NOT_SUPPORTED = (4102, "不支持的音色")
    TEXT_TOO_LONG = (4103, "文本过长")
    INVALID_TEXT = (4104, "文本内容无效")
    AUDIO_GENERATION_FAILED = (4105, "音频生成失败")
    TEXT_EMPTY = (4106, "文本内容为空")


class STTErrorCode(BaseCodeEnum):
    """
    STT相关错误码枚举
    
    定义语音转文本服务相关的错误码
    """

    CONVERSION_FAILED = (4201, "语音转文本失败")
    AUDIO_NOT_FOUND = (4202, "音频文件未找到")
    INVALID_AUDIO_FORMAT = (4203, "音频格式无效")
    LANGUAGE_NOT_SUPPORTED = (4204, "不支持的语音语言")
    TIMEOUT = (4205, "语音转文本超时")
    EMPTY_AUDIO = (4206, "音频内容为空")
    AUDIO_TOO_LONG = (4207, "音频时长过长")
    AUDIO_PATH_EMPTY = (4208, "音频文件路径不能为空")
    STT_TIME_OUT = (4209, "STT处理超时")


class VPErrorCode(BaseCodeEnum):
    """
    声纹识别相关错误码枚举

    定义声纹识别服务相关的错误码
    """

    CONVERSION_FAILED = (4301, "声纹识别失败")
    AUDIO_NOT_FOUND = (4302, "音频文件未找到")


class FileErrorCode(BaseCodeEnum):
    """
    文件操作错误码枚举
    
    定义文件操作相关的错误码
    """

    NOT_FOUND = (5001, "文件未找到")
    READ_ERROR = (5002, "文件读取错误")
    WRITE_ERROR = (5003, "文件写入错误")
    DELETE_ERROR = (5004, "文件删除错误")
    INVALID_PATH = (5005, "文件路径无效")
    PERMISSION_DENIED = (5006, "文件权限不足")


class NetworkErrorCode(BaseCodeEnum):
    """
    网络错误码枚举
    
    定义网络通信相关的错误码
    """

    TIMEOUT = (5101, "网络超时")
    CONNECTION_FAILED = (5102, "网络连接失败")
    REQUEST_FAILED = (5103, "请求失败")
    RESPONSE_INVALID = (5104, "响应无效")


class ModelErrorCode(BaseCodeEnum):
    """
    模型相关错误码枚举
    
    定义AI模型操作相关的错误码
    """

    LOAD_FAILED = (5201, "模型加载失败")
    NOT_FOUND = (5202, "模型未找到")
    INFERENCE_FAILED = (5203, "模型推理失败")
    UNSUPPORTED_MODEL = (5204, "不支持的模型类型")
    MODEL_OUTDATED = (5205, "模型版本过期")


class ConfigErrorCode(BaseCodeEnum):
    """
    配置错误码枚举
    
    定义配置管理相关的错误码
    """

    INVALID = (5301, "配置无效")
    MISSING = (5302, "配置缺失")
    PARSE_ERROR = (5303, "配置解析错误")
    VALIDATION_FAILED = (5304, "配置验证失败")


class ServiceStatusCode(BaseCodeEnum):
    """
    服务状态码枚举
    
    定义服务运行状态相关的状态码
    """

    INITIALIZING = (1001, "服务初始化中")
    RUNNING = (1002, "服务运行中")
    STOPPING = (1003, "服务停止中")
    STOPPED = (1004, "服务已停止")
    RESTARTING = (1005, "服务重启中")
    HEALTH_CHECK_FAILED = (1006, "健康检查失败")


class ReturnCodes:
    """
    返回码工具类
    
    提供向后兼容的常量访问和实用方法
    同时支持新的枚举类型和旧的常量访问方式
    """

    # 向后兼容的常量定义
    SUCCESS = ReturnCode.SUCCESS.code
    OK = ReturnCode.OK.code
    BAD_REQUEST = ReturnCode.BAD_REQUEST.code
    UNAUTHORIZED = ReturnCode.UNAUTHORIZED.code
    FORBIDDEN = ReturnCode.FORBIDDEN.code
    NOT_FOUND = ReturnCode.NOT_FOUND.code
    METHOD_NOT_ALLOWED = ReturnCode.METHOD_NOT_ALLOWED.code
    INTERNAL_SERVER_ERROR = ReturnCode.INTERNAL_SERVER_ERROR.code
    SERVICE_UNAVAILABLE = ReturnCode.SERVICE_UNAVAILABLE.code
    GATEWAY_TIMEOUT = ReturnCode.GATEWAY_TIMEOUT.code

    # 通用错误码
    INVALID_PARAMETER = GeneralErrorCode.INVALID_PARAMETER.code
    MISSING_PARAMETER = GeneralErrorCode.MISSING_PARAMETER.code
    INVALID_FORMAT = GeneralErrorCode.INVALID_FORMAT.code
    PERMISSION_DENIED = GeneralErrorCode.PERMISSION_DENIED.code

    # TTS相关错误码
    TTS_CONVERSION_FAILED = TTSErrorCode.CONVERSION_FAILED.code
    TTS_VOICE_NOT_SUPPORTED = TTSErrorCode.VOICE_NOT_SUPPORTED.code
    TTS_TEXT_TOO_LONG = TTSErrorCode.TEXT_TOO_LONG.code

    # STT相关错误码
    STT_CONVERSION_FAILED = STTErrorCode.CONVERSION_FAILED.code
    STT_AUDIO_NOT_FOUND = STTErrorCode.AUDIO_NOT_FOUND.code
    STT_INVALID_AUDIO_FORMAT = STTErrorCode.INVALID_AUDIO_FORMAT.code
    STT_LANGUAGE_NOT_SUPPORTED = STTErrorCode.LANGUAGE_NOT_SUPPORTED.code
    STT_TIMEOUT = STTErrorCode.TIMEOUT.code
    STT_EMPTY_AUDIO = STTErrorCode.EMPTY_AUDIO.code

    # 文件操作错误码
    FILE_NOT_FOUND = FileErrorCode.NOT_FOUND.code
    FILE_READ_ERROR = FileErrorCode.READ_ERROR.code
    FILE_WRITE_ERROR = FileErrorCode.WRITE_ERROR.code
    FILE_DELETE_ERROR = FileErrorCode.DELETE_ERROR.code

    # 网络错误码
    NETWORK_TIMEOUT = NetworkErrorCode.TIMEOUT.code
    NETWORK_CONNECTION_FAILED = NetworkErrorCode.CONNECTION_FAILED.code

    # 模型相关错误码
    MODEL_LOAD_FAILED = ModelErrorCode.LOAD_FAILED.code
    MODEL_NOT_FOUND = ModelErrorCode.NOT_FOUND.code
    MODEL_INFERENCE_FAILED = ModelErrorCode.INFERENCE_FAILED.code

    # 配置错误码
    CONFIG_INVALID = ConfigErrorCode.INVALID.code
    CONFIG_MISSING = ConfigErrorCode.MISSING.code

    # 服务状态码
    SERVICE_INITIALIZING = ServiceStatusCode.INITIALIZING.code
    SERVICE_RUNNING = ServiceStatusCode.RUNNING.code
    SERVICE_STOPPING = ServiceStatusCode.STOPPING.code
    SERVICE_STOPPED = ServiceStatusCode.STOPPED.code

    # 状态码描述映射（向后兼容）
    _CODE_DESCRIPTIONS = {
        SUCCESS: "操作成功",
        OK: "操作成功",
        BAD_REQUEST: "请求参数错误",
        UNAUTHORIZED: "未授权访问",
        FORBIDDEN: "禁止访问",
        NOT_FOUND: "资源未找到",
        METHOD_NOT_ALLOWED: "方法不被允许",
        INTERNAL_SERVER_ERROR: "服务器内部错误",
        SERVICE_UNAVAILABLE: "服务不可用",
        GATEWAY_TIMEOUT: "网关超时",
        INVALID_PARAMETER: "参数无效",
        MISSING_PARAMETER: "缺少必要参数",
        INVALID_FORMAT: "格式无效",
        TTS_CONVERSION_FAILED: "文本转语音失败",
        TTS_VOICE_NOT_SUPPORTED: "不支持的音色",
        TTS_TEXT_TOO_LONG: "文本过长",
        STT_CONVERSION_FAILED: "语音转文本失败",
        STT_AUDIO_NOT_FOUND: "音频文件未找到",
        STT_INVALID_AUDIO_FORMAT: "音频格式无效",
        STT_LANGUAGE_NOT_SUPPORTED: "不支持的语音语言",
        STT_TIMEOUT: "语音转文本超时",
        STT_EMPTY_AUDIO: "音频内容为空",
        FILE_NOT_FOUND: "文件未找到",
        FILE_READ_ERROR: "文件读取错误",
        FILE_WRITE_ERROR: "文件写入错误",
        FILE_DELETE_ERROR: "文件删除错误",
        NETWORK_TIMEOUT: "网络超时",
        NETWORK_CONNECTION_FAILED: "网络连接失败",
        MODEL_LOAD_FAILED: "模型加载失败",
        MODEL_NOT_FOUND: "模型未找到",
        MODEL_INFERENCE_FAILED: "模型推理失败",
        CONFIG_INVALID: "配置无效",
        CONFIG_MISSING: "配置缺失",
        PERMISSION_DENIED: "权限被拒绝",
        SERVICE_INITIALIZING: "服务初始化中",
        SERVICE_RUNNING: "服务运行中",
        SERVICE_STOPPING: "服务停止中",
        SERVICE_STOPPED: "服务已停止",
    }

    @classmethod
    def get_description(cls, code: int) -> str:
        """
        获取状态码描述（向后兼容）
        
        Args:
            code (int): 状态码
            
        Returns:
            str: 状态码描述
        """
        # 优先使用枚举查找
        enum_desc = cls._get_enum_description(code)
        if enum_desc:
            return enum_desc

        # 回退到兼容映射
        return cls._CODE_DESCRIPTIONS.get(code, f"未知状态码: {code}")

    @classmethod
    def _get_enum_description(cls, code: int) -> Optional[str]:
        """通过枚举获取描述信息"""
        # 尝试所有枚举类
        for enum_class in [ReturnCode, GeneralErrorCode, TTSErrorCode,
                           STTErrorCode, FileErrorCode, NetworkErrorCode,
                           ModelErrorCode, ConfigErrorCode, ServiceStatusCode]:
            enum_item = enum_class.get_by_code(code)
            if enum_item:
                return enum_item.message
        return None

    @classmethod
    def is_success(cls, code: int) -> bool:
        """
        判断是否为成功状态码
        
        Args:
            code (int): 状态码
            
        Returns:
            bool: 是否为成功状态码
        """
        return code == cls.SUCCESS

    @classmethod
    def is_client_error(cls, code: int) -> bool:
        """
        判断是否为客户端错误码
        
        Args:
            code (int): 状态码
            
        Returns:
            bool: 是否为客户端错误码
        """
        return 400 <= code < 500

    @classmethod
    def is_server_error(cls, code: int) -> bool:
        """
        判断是否为服务器错误码
        
        Args:
            code (int): 状态码
            
        Returns:
            bool: 是否为服务器错误码
        """
        return 500 <= code < 600

    @classmethod
    def get_enum_by_code(cls, code: int) -> Optional[BaseCodeEnum]:
        """
        根据状态码获取对应的枚举实例
        
        Args:
            code (int): 状态码
            
        Returns:
            Optional[BaseCodeEnum]: 对应的枚举实例，找不到返回None
        """
        # 尝试所有枚举类
        for enum_class in [ReturnCode, GeneralErrorCode, TTSErrorCode,
                           STTErrorCode, FileErrorCode, NetworkErrorCode,
                           ModelErrorCode, ConfigErrorCode, ServiceStatusCode]:
            enum_item = enum_class.get_by_code(code)
            if enum_item:
                return enum_item
        return None

    @classmethod
    def get_all_codes(cls) -> Dict[int, str]:
        """
        获取所有状态码及其描述的映射
        
        Returns:
            Dict[int, str]: 状态码到描述的映射字典
        """
        all_codes = {}

        # 收集所有枚举的状态码
        for enum_class in [ReturnCode, GeneralErrorCode, TTSErrorCode,
                           STTErrorCode, FileErrorCode, NetworkErrorCode,
                           ModelErrorCode, ConfigErrorCode, ServiceStatusCode]:
            for item in enum_class:
                all_codes[item.code] = item.message

        return all_codes


# 创建快捷引用（向后兼容）
RC = ReturnCodes
